<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.userName" placeholder="用户名">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="密码" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="captcha" v-if="validateCaptcha">
      <div class="captcha-container">
        <el-image :src="captchaUrl" @click="getCaptcha" class="captcha-image"></el-image>
        <el-input v-model="loginForm.captcha" placeholder="验证码" class="captcha-input">
          <template #prefix>
            <el-icon class="el-input__icon">
              <edit />
            </el-icon>
          </template>
        </el-input>
      </div>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置</el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import type { ElForm } from "element-plus";
import { ElNotification } from "element-plus";
import { loginApi, captchaApi, ReqLoginForm } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import { generateUUID, getTimeState } from "@/utils";
import { getConfigValueByKey } from "@/api/modules/sys/SysConfig";
import { getSelfInfo } from "@/api/modules/sys/user";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<ReqLoginForm>({
  userName: "super-admin",
  password: "123456",
  uuid: "",
  captcha: ""
});

// 验证码
const captchaUrl = ref<any>("#");
const validateCaptcha = ref<boolean>();

async function getCaptcha() {
  if (!validateCaptcha.value) {
    let { data } = await getConfigValueByKey("VALIDATE_CAPTCHA");
    validateCaptcha.value = data === "true";
  }
  if (validateCaptcha.value) {
    loginForm.uuid = generateUUID();
    const blob: any = await captchaApi(loginForm.uuid);
    captchaUrl.value = window.URL.createObjectURL(blob.data);
  }
}

// 初始化验证码
getCaptcha();

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const { data } = await loginApi({ ...loginForm });
      userStore.setToken(data.tokenValue);
      userStore.setTokenName(data.tokenName);
      // 获取当前用户信息
      const selfData = (await getSelfInfo()).data;
      userStore.setUserInfo({ name: selfData.nickName });

      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录 " + selfData.nickName,
        type: "success",
        duration: 3000
      });
    } finally {
      loading.value = false;
      getCaptcha();
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});
</script>

<style scoped lang="scss">
@import "../index";

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-image {
  width: 200px; /* 设置验证码图片的宽度 */
  height: 40px; /* 设置验证码图片的高度 */
  margin-right: 10px; /* 调整图片和输入框之间的间距 */
}

.captcha-input {
  flex: 1; /* 使输入框占据剩余的空间 */
}
</style>
